<template>
  <div>
    <el-card shadow="never" :body-style="{ padding: '0px' }">
      <div slot="header">
        <el-row :gutter="10" type="flex" justify="start">
            <el-col :span="3">
            <el-form :model='dropList'>
          <el-select v-model="dropList.id" placeholder="请选择" clearable
          @change="selectTrigger1(dropList.id)">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
            </el-form>
          </el-col>
          <el-col :span="9">
             <el-form :model='content'> 
               <el-form-item prop='name' label=''> 
                <el-input v-model='content.name' placeholder="题目" clearable></el-input>
               </el-form-item> 
            </el-form> 
          </el-col>
          <el-col :span="35">
            <el-button type="primary" icon="el-icon-search" @click="query()">查询</el-button>
          </el-col>
          <el-col :span="40">
            <el-button type="primary" icon="el-icon-plus" @click="dialogAddVisible = true">新增</el-button>
           </el-col>
        </el-row>
      </div>
      <el-table :data="pager.content" style="width: 100%" stripe highlight-current-row v-loading="$store.state.loading" @selection-change="onSelectionChange"
      :default-sort= "{prop:'date',order:'descending'}" >
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column prop="title" label="题目" ></el-table-column>
        <el-table-column type="expand">
            <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                    <el-form-item label="题目内容:" style="color:red">
                    <span>&nbsp;&nbsp;{{ props.row.content }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    </el-form-item>
                    <el-form-item label="题目答案:" style="color:red">
                    <span>&nbsp;&nbsp;{{ props.row.answer }}</span>
                    </el-form-item>
                </el-form>
            </template>
        </el-table-column>
        <el-table-column prop="questionType.name" label="题型" ></el-table-column>
        <el-table-column prop="questionScore" label="分数" ></el-table-column>
        <el-table-column prop="created.nickname" label="出题人" ></el-table-column>
        <el-table-column label="修改日期" sortable  prop="updateDate" align="center">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left:5px">{{ scope.row.updateDate | moment('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建日期" sortable  prop="creationDate" align="center">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left:5px">{{ scope.row.creationDate | moment('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="310" align="center">
          <template slot-scope="scope">
            <el-button size='medium' type="warning" @click='handleEditRow(scope.$index, scope.row)'>编辑</el-button>
            <el-button size='medium' type="danger" @click="remove(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange" 
          :page-size="pager.pageable.pageSize" 
          :total="pager.totalElements" 
          class="pagination text-right" 
          :page-sizes="$store.state.paginationPageSizes" 
          :layout="$store.state.paginationLayout">
      </el-pagination>
    </el-card>

    <el-dialog title="编辑试题" :visible.sync="dialogVisible">
      <el-form :label-position="'right'" label-width="80px" ref="userForm" :model="userForm" :rules="rules_update">
        <el-form-item label="题目名称" prop="title">
          <el-input placeholder="请输入题目名称" v-model="userForm.title"></el-input>
        </el-form-item>
         <el-form-item label="题目类型">
          <el-select v-model="userForm.questionType.id" placeholder="请选择" clearable
           @change="selectTrigger(userForm.questionType.id)">
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分数" prop="questionScore">
          <el-input-number type="text" :min="0"  v-model="userForm.questionScore"></el-input-number>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type='textarea' v-model="userForm.content" rows="10" clearable></el-input>
        </el-form-item>
        <el-form-item label="答案">
          <el-input id="input" type='textarea' v-model="userForm.answer" rows="4" clearable style="display:block"></el-input>
          <template>
              <div id="div" style="display:none">
                <el-radio v-model="userForm.answer" label="A">A</el-radio>
                <el-radio v-model="userForm.answer" label="B">B</el-radio>
                <el-radio v-model="userForm.answer" label="C">C</el-radio>
                <el-radio v-model="userForm.answer" label="D">D</el-radio>
              </div>
            </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="update('userForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="新增试题" :visible.sync="dialogAddVisible" >
      <el-form :label-position="'right'" label-width="80px" ref="userForm_add" :model="userForm_add" :rules="rules_add">
        <el-form-item label="题目名称" prop="title">
          <el-input placeholder="请输入题目名称" v-model="userForm_add.title"></el-input>
        </el-form-item>
        <el-form-item label="题目类型">
          <el-select v-model="userForm_add.questionType.id" placeholder="请选择" clearable
           @change="selectTrigger(userForm_add.questionType.id)">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分数" prop="questionScore">
          <el-input-number type="text" :min="0" v-model="userForm_add.questionScore"></el-input-number>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type='textarea' v-model="userForm_add.content" rows="10" clearable></el-input>
        </el-form-item>
        <el-form-item label="答案">
          <el-input id="input" type='textarea' v-model="userForm_add.answer" rows="4" clearable style="display:block"></el-input>
          <template>
              <div id="div" style="display:none">
                <el-radio v-model="userForm_add.answer" label="A">A</el-radio>
                <el-radio v-model="userForm_add.answer" label="B">B</el-radio>
                <el-radio v-model="userForm_add.answer" label="C">C</el-radio>
                <el-radio v-model="userForm_add.answer" label="D">D</el-radio>
              </div>
            </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit('userForm_add')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title='提示' width='25%' :visible.sync='deleteVisible'>
            <span>确定执行数据删除操作 ? </span>
            <span slot='footer'>
                <el-button type='text' @click='deleteVisible=false'>取消</el-button>
                <el-button type='primary' @click='handleDeleteConfirm'>确定</el-button>
            </span>
        </el-dialog>
    <el-dialog title='菜单'  :visible.sync='menuVisible' width='40%'>
            <el-transfer v-model='currentMenus' :data='allRoles' :props="{key:'id',label:'name'}" :titles="['未分配角色', '已分配角色']" filterable 
            style="text-align: left; display: inline-block;margin-left:90px;">
            </el-transfer>
            <div slot='footer'>
                <el-button @click='menuVisible=false'>取消</el-button>
                <el-button type='primary' @click='handleMenuSubmit'>确定</el-button>
            </div>
  </el-dialog>
  </div>

  
</template>
<style>
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
<script>
export default {
  data() {
    var validateUpdateName = (rule,value,callback) => {
      if(typeof(value) == "undefined" || value == "")
      {
        callback(new Error('请输入角色名称'));
      }else{
        if(value == this.roleName){
          callback();
        }else{
          this.$http.get("/api/accounts/isExit",{params:{'name':value}}).then(res => {
          if(res.data == true){
              callback();
          }else{
              callback(new Error('该角色名称已经存在'));
          }
        })
        }
      }
    }
    return {
        dropList:new Object(),
        radio:'1',
        radio1: '1',
    options:new Object(),
    options1: new Object(),
      total:'',
      size: '',
      content : new Object(),
      currentData: new Object(),
      userForm : {title:"",answer:"",questionType:{id:"",name:""},created:{id:""},questionScore:""},
      userForm_add : {title:"",answer:"",questionType:{id:"",name:""},created:{id:""},questionScore:10},
      deleteVisible: false,
      dialogVisible: false,
      dialogAddVisible: false,
      menuVisible: false,
      currentData:new Object() ,
      currentMenus : new Array() ,
      allRoles : new Array() ,
      tabledata : new Array() ,
      state: null,
      dateRange: null,
      roleName:"",
      userId : this.$store.state.userId ,
      selectedRows: [],
      bucketName: "public",
      pager: {pageable:[], totalElements: 0, content: [] },
      rules_add: {title:[{required:true,message:'请输入试题名称..',trigger:'blur'}],
                    questionScore:[{required:true,message:'请输入试题分数..',trigger:'blur'}]},
      rules_update: {title:[{required:true,message:'请输入试题名称..',trigger:'blur'}]
                    ,questionScore:[{required:true,message:'请输入试题分数..',trigger:'blur'}]}
    };
  },
  mounted() {
    this.query();
    this.getDropList();
  },
  methods: {
    getDropList() {
        this.$http.get('/api/testQuestions/dropList').then(res => {
            this.options = res.data;
            this.options1 = res.data;
        })
    },
    query() {
        if(this.content && this.content.name && !this.dropList.id)
        {
            this.$http.get('/api/testQuestions/',{params:{"page":this.pager.pageable.pageNumber,"size":this.pager.pageable.pageSize,"title":this.content.name}}).then(res => {
                this.pager = res.data;
            })
        }else if(this.content && this.content.name && this.dropList.id)
        {
            this.$http.get('/api/testQuestions/both',{params:{"page":this.pager.pageable.pageNumber,"size":this.pager.pageable.pageSize,"title":this.content.name,"questionTypeId":this.dropList.id}}).then(res => {
                this.pager = res.data;
            })
        }else if (this.dropList.id && !this.content.name)
        {
            this.$http.get('/api/testQuestions/',{params:{"questionTypeId":this.dropList.id,"page":this.pager.pageable.pageNumber,"size":this.pager.pageable.pageSize}}).then(res => {
                if(res.status == 200)
                {
                    this.pager = res.data;
                }
            })
        }else{
            this.$http.get('/api/testQuestions/',{params:{"page":this.pager.pageable.pageNumber,"size":this.pager.pageable.pageSize}}).then(res => {
            this.pager = res.data;
        })
        }
        
    },
    handleEditRow(index,row) {
      this.roleName = row.name;
      this.dialogVisible = true;
      this.userForm = Object.assign({},row) ;
    },
    onSelectionChange(rows) {
      this.selectedRows = rows.map(item => item.userId);
    },
    remove(index,row) {
      this.deleteVisible = true ;
      this.currentData = row;
    },
    onRemoveFile(file) {
      this.$http.delete(`/oss/remove/${this.bucketName}/${file.response}`);
    },
    handleSizeChange(val) {
        this.$http.get("/api/testQuestions/",{params:{"size":val,"pageable":'1'}}).then(res => {
        this.pager = res.data;
      });
      },
    handleCurrentChange(val) {
        this.$http.get("/api/testQuestions/",{params:{"page":val-1,"size":this.pager.pageable.pageSize,"pageable":'1'},}).then(res => {
        this.pager = res.data;
        });
      },
    onSubmit(userForm)
    {
      this.$refs[userForm].validate((valid) => {
        if(valid)
        {
            this.userForm_add.created.id = this.userId;
          this.$http.post("/api/testQuestions/",this.userForm_add).then(res => {
            if(res.status == 200)
            {
              this.$notify({type:'success',title:'成功',message:'添加成功'}) ;
              this.dialogAddVisible = false;
              this.userForm_add =  {title:"",answer:"",questionType:{id:"",name:""},created:{id:""}};
              this.query();
            }
          })
        }
      })
    },update(userForm){
        this.$refs[userForm].validate((valid) => {
            if(valid)
            {
                this.$http.put("/api/testQuestions/"+this.userForm.id,this.userForm).then(res => {
                    if(res.status == 200)
                    {
                        this.$notify({type:'success',title:'成功',message:'更新成功'}) ;
                        this.dialogVisible = false;
                        this.userForm =  {title:"",answer:"",questionType:{id:"",name:""},created:{id:""}};
                        this.query();
                    }
                })
            }
        })
    },
    handleDeleteConfirm(){
      this.$http.delete("/api/testQuestions/"+this.currentData.id).then(res => {
        if(res.status == 204)
        {
          this.deleteVisible = false;
          this.currentData = {};
          this.query();
        }
      })
    },
    addRole(index,row){
      this.currentData = row ;
      this.$http.get("/api/roles/noPage").then(res => {
        this.allRoles = res.data;
        let foo = Object.assign([],this.currentData.roles) ;
        this.currentMenus = foo && foo.length>0 ? foo.map(x=>x.id) : new Array() ;
        this.menuVisible = true ;
      }).catch(error=>console.error(error))
    }
    ,
    handleMenuSubmit() {
                let o = Object.assign([],this.currentMenus) .map(x=>{ return { id : x }; });
                let i = this.tabledata.findIndex( x=> x.id==this.currentData.id ) ;

                this.$http.put("/api/accounts/"+this.currentData.id+"/roles", o)
                    .then(res=>{
                        this.currentData = res.data ;
                        this.tabledata.splice( i , 1 , this.currentData) ;
                        this.menuVisible = false ;
                        this.query();
                        this.$notify({type:'success',title:'成功',message:'关联角色成功'}) ;
                    })
                    .catch(error=>console.error(error))
                ;
            },
    selectTrigger(value)
    {
        if(value)
        {
            this.$http.get('/api/testQuestions/'+value).then(res=>{
                if(res.data.name == "选择题"){
                    document.getElementById('input').style.display="none";
                    document.getElementById('div').style.display="block";
                }else if (res.data.name == "SQL题"){
                    document.getElementById('input').style.display="block";
                    document.getElementById('div').style.display="none";
                }
            })
        }
    },
    selectTrigger1(value)
    {
        if(value)
        {
            this.$http.get('/api/testQuestions',{params:{"questionTypeId":value,"page":this.pager.pageable.pageNumber,"size":this.pager.pageable.pageSize}}).then(res => {
                if(res.status == 200)
                {
                    this.pager = res.data;
                }
            })
        }
    }
  },
};
</script>